import { Notification, MessageBox, Message, Loading } from "element-ui";
import { tansParams, blobValidate } from "@/utils/ruoyi";
import { saveAs } from 'file-saver'
export default function ({ $axios, redirect, app },inject) {
  let downloadLoadingInstance;
  // 通用下载方法
  function download(url, params, filename, config) {
    downloadLoadingInstance = Loading.service({
      text: app.i18n.t("common.requestTips4"),
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    return  $axios
      .post(url, params, {
        transformRequest: [
          (params) => {
            return tansParams(params);
          },
        ],
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        responseType: "blob",
        ...config,
      })
      .then(async (data) => {
        console.log('download data', data)
        const isLogin = await blobValidate(data);
        if (isLogin) {
          const blob = new Blob([data]);
          saveAs(blob, filename);
        } else {
          const resText = await data.text();
          const rspObj = JSON.parse(resText);
          const errMsg =
            errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
          // 国际化报错：抱歉，您没有下载权限，请联系客服！
          console.log('errMsg', errMsg)
          Message.error(app.i18n.t(errMsg));
        }
        downloadLoadingInstance.close();
      })
      .catch((r) => {
        Message.error(app.i18n.t("common.requestTips5"));
        downloadLoadingInstance.close();
      });
  }
  inject('download',download)
}
